package com.zy.pigchat_server.socketServer;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 这是那头猪？
 * @version 1.0
 * @description:
 * @date 2023/7/28 13:40
 */
@Slf4j
@Component
@ServerEndpoint("/websocket/{userName}")
public class MyWebSocket {
    

    /**
     * 在线人数
     */
    public static int onlineNumber = 0;

    /**
     * 以id为key，MyWebSocket为对象保存起来
     */
    private static Map<String, MyWebSocket> clients = new ConcurrentHashMap<>();

    /**
     * 会话
     */
    private Session session;

    /**
     * 用户名称
     */
    private String userName;

    /**
     * 建立连接
     * @param userName  用户名
     * @param session   用户会话的session
     */
    @OnOpen
    public void onOpen(@PathParam(value = "userName") String userName, Session session) {
        Map<String, List<String>> requestParameterMap = session.getRequestParameterMap();

        onlineNumber++;
        this.userName = userName;
        this.session = session;
        clients.put(userName, this);
        log.info("有新连接加入！当前在线人数" + onlineNumber);
        sendUserNumberAll();
    }

    /**
     * 连接发生错误的时候
     * @param error 错误异常
     */
    @OnError
    public void onError(Throwable error) {
        log.info("服务端发生了错误" + error.getMessage());
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose() {
        onlineNumber--;
        log.info("有连接关闭！ 当前在线人数" + onlineNumber);
    }

    /**
     * 收到客户端的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            System.out.println(message);
            sendMessageAll(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送给当个用户
     * @param message
     * @param userName
     * @throws IOException
     */
    public void sendMessageTo(String message, String userName) throws IOException {
        for (MyWebSocket item : clients.values()) {
            if (item.userName.equals(userName)) {
                try {
                    Map map = JSONUtil.toBean(message, Map.class);
                    map.put("number", onlineNumber);
                    item.session.getAsyncRemote().sendText(JSONUtil.toJsonStr(map));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    // e.printStackTrace();
                }
                break;
            }
        }
    }

    /**
     * 发送给全部用户
     * @param message
     * @throws IOException
     */
    public void sendMessageAll(String message) throws IOException {
        //广播信息
        for (MyWebSocket item : clients.values()) {
            try {
                Map map = JSONUtil.toBean(message, Map.class);
                map.put("number", onlineNumber);
                item.session.getAsyncRemote().sendText(JSONUtil.toJsonStr(map));
            } catch (Exception e) {
                System.out.println(e.getMessage());
                // e.printStackTrace();
            }
        }
    }

    /**
     * 发送给全部用户 全部人数 和头像
     * @throws IOException
     */
    public void sendUserNumberAll( ) {
        //广播 人数
        for (MyWebSocket item : clients.values()) {
            try {
                Map map = new HashMap<>();
                map.put("number", onlineNumber);
                item.session.getAsyncRemote().sendText(JSONUtil.toJsonStr(map));
            } catch (Exception e) {
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取在线人数
     * @return
     */
    public static synchronized int getOnlineCount() {
        return onlineNumber;
    }

}